const { exec } = require('../db/mysql') // 引入统一执行函数

// 获取文章的列表
const getList = async (author, keyword) => {
  let sql = 'select id,title,content,author,createtime from blogs where 1=1'
  if (author) {
    sql += ` and author='${author}'`
  }
  if (keyword) {
    sql += ` and title like '%${keyword}%'`
  }
  sql += ` order by createtime desc;`
  const articleList = await exec(sql)
  return articleList
}

// 获取文章的详情
const getDetail = async (id) => {
  const sql = `select * from blogs where id=${id};`
  const articleDetail = await exec(sql).then(rows => rows[0])
  return articleDetail
}

// 新建博客
const newBlog = async (blogData = {}) => {
  const { title, content, author } = blogData
  const createtime = Date.now()
  const sql = `insert into blogs (title,content,author,createtime) values ('${title}','${content}','${author}','${createtime}');`
  const newedBlog = await exec(sql).then(insertData => ({ id: insertData.insertId }))
  return newedBlog
}

// 更新博客
const updateBlog = async (id, blogData = {}) => {
  const { title, content } = blogData
  const createtime = Date.now()
  const sql = `update blogs set title='${title}',content='${content}',createtime='${createtime}' where id=${id};`
  const updatedBlog = await exec(sql).then(updateData => {
    if (updateData.affectedRows > 0) {
      return '修改成功'
    }
    return '失败'
  })
  return updatedBlog
}

// 删除博客
const deleteBlog = async (id, author) => {
  const sql = `delete from blogs where id='${id}' and author='${author}';`
  const deletedBlog = await exec(sql).then(deleteData => {
    return deleteData.affectedRows > 0
      ? '成功'
      : '失败'
  })
  return deletedBlog
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  deleteBlog,
}